using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ExpandUI : MonoBehaviour
{
    [SerializeField] RectTransform layoutRoot;
    [SerializeField] RectTransform content;

    private float expandTime = 0.2f;

    bool isOpen;

    public void SwithPanel()
    {
        isOpen=!isOpen;
        if( isOpen )
        {
            Expand();
        }
        else
        {
            Shirk();
        }
        
    }
    public void Expand()
    {
       StartCoroutine(ExpandCoroutie());    
    }

    IEnumerator ExpandCoroutie()
    {
        float currentTime = 0;
        //float contentHeight=content.rect.height;
        float contentHeight=400;

        RectTransform rectTransform = (RectTransform)transform;
        rectTransform.sizeDelta=new Vector2(rectTransform.sizeDelta.x, 0);

        Vector2 targetSize=new Vector2(rectTransform.sizeDelta.x, contentHeight);

        while(currentTime < expandTime)
        {
            currentTime+=Time.deltaTime;
            rectTransform.sizeDelta=Vector2.Lerp(rectTransform.sizeDelta, targetSize, currentTime/expandTime);

            //刷新尺寸
            LayoutRebuilder.ForceRebuildLayoutImmediate(layoutRoot);
            yield return null;
        }
    }
    public void Shirk()
    {
        StartCoroutine(ShirkCoroute());
    }
    IEnumerator ShirkCoroute()
    {
        float currentTime = 0;
      //  float contentHeight = content.rect.height;
        float contentHeight = 400;

        RectTransform rectTransform = (RectTransform)transform;
        rectTransform.sizeDelta=new Vector2(rectTransform.sizeDelta.x, contentHeight);

        Vector2 targetSize = new Vector2(rectTransform.sizeDelta.x, 0);

        while (currentTime < expandTime)
        {
            currentTime+=Time.deltaTime;
            rectTransform.sizeDelta=Vector2.Lerp(rectTransform.sizeDelta, targetSize, currentTime/expandTime);
            yield return null;
        }
    }
}
